<template>
  <div>
    <form-content
      ref="actForm"
      :rules="formItems2Rules"
      :form-items="formItems"
      :submitApi="detail.id ? update : add"
      :afterSubmit="afterSubmit"
      :beforeSubmit="beforeSubmit"
      :formStateInit="detail"
      @get:formState="getFormState"
    >
      <template #module="{ item, formState }">
        <div class="">
          <a-form-item label="图片">
            <Uploader v-model:value="formState.module.PIC" :maxLen="10" />
          </a-form-item>
          <a-form-item label="视频">
            <video-uploader
              v-model:value="formState.module.VIDEO"
              tip="上传视频大小最大100M, 最多10个"
              :maxLen="10"
            />
          </a-form-item>
        </div>
      </template>
      <template #img="{ item, formState }">
        <div class="">
          <Uploader v-model:value="formState.img" :maxLen="1" />
        </div>
      </template>
      <template #tasks="{ item, formState }">
        <a-space direction="vertical" style="width: 100%">
          <a-button type="primary" @click="showTaskModal()">
            添加任务
          </a-button>
          <a-table
            :dataSource="formState.tasks"
            :columns="taskCols"
            row-key="key"
            :pagination="false"
          >
            <template #action="{ text, record }">
              <a @click="showTaskModal(record)">编辑</a>
              <a-divider type="vertical" />
              <a
                style="color: #f00"
                @click="
                  changeStatus(
                    record.status == 'STATUS_PUT_SHELF'
                      ? 'STATUS_OFF_SHELF'
                      : 'STATUS_PUT_SHELF',
                    record
                  )
                "
              >
                {{ record.status == 'STATUS_PUT_SHELF' ? '下架' : '上架' }}
              </a>
            </template>
          </a-table>
        </a-space>
      </template>
    </form-content>
    <TaskModal
      ref="taskmodal"
      @sure="ok"
      :task="modalTask"
      :modalTasks="modalTasks"
    />
  </div>
</template>

<script>
  import {
    ref,
    toRefs,
    reactive,
    watch,
    onMounted,
    onUnmounted,
    getCurrentInstance,
  } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import moment from 'moment';
  import { taskCols } from './config';
  import { formItems, formItems2Rules } from './config';
  import { add, update, info } from './api';
  import TaskModal from './taskModal.vue';

  const TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss';

  export default {
    components: {
      TaskModal,
    },

    data() {
      return {
        add,
        update,
        info,
        formItems,
        formItems2Rules,
        taskCols,
      };
    },
    setup(props, context) {
      const internalInstance = getCurrentInstance();
      const route = useRoute();
      const router = useRouter();
      const actForm = ref(null);
      const taskmodal = ref(null);
      const state = reactive({
        modalTask: {},
        detail: {},
        modalTasks: [],
      });

      const getTaskTypeName = (type) => {
        switch (type) {
          case 'TASK_TYPE_SHARE':
            return '分享类';
          case 'TASK_TYPE_WEB':
            return '网页类';
          case 'TASK_TYPE_VIDEO':
            return '视频类';
          case 'TASK_TYPE_NEWS':
            return '新闻类';
        }
      };

      const geiDetail = () => {
        info({
          id: Number(route.params.id),
        }).then((res) => {
          state.detail = {
            ...res.data,
            at: [
              moment(res.data.start_at * 1000),
              moment(res.data.end_at * 1000),
            ],
            use_at: [
              moment(res.data.use_start_at * 1000),
              moment(res.data.use_end_at * 1000),
            ],
            img: [res.data.img],
            module: {
              PIC: [],
              VIDEO: [],
            },
            tasks: res.data.tasks.map((m) => ({
              ...m,
              key: m.id,
              type_name: getTaskTypeName(m.type),
            })),
          };
          res.data.module.forEach((item) => {
            if (item.type == 'PIC') {
              state.detail.module.PIC.push(item.pic);
            } else {
              state.detail.module.VIDEO.push({
                url: item.video_info.url,
                video_id: item.video_info.video_id,
                uid: item.video_info.id,
                name: item.video_info.title.substr(0, 20),
              });
            }
          });
        });
      };

      onMounted(() => {
        if (route.params.id) {
          geiDetail();
        } else {
          state.detail = {};
        }
      });

      const afterSubmit = (res) => {
        router.push('/space/activity/list');
      };

      onUnmounted(() => {
        formItems.forEach((item) => {
          if (item.name == 'module') {
            item.value = {
              PIC: [],
              VIDEO: [],
            };
          }
        });
      });

      const beforeSubmit = (params) => {
        if (route.params.id) {
          params.id = parseInt(route.params.id);
        }
        params.img = {
          upload_channel: params.img[0].upload_channel,
          bucket: params.img[0].bucket,
          img_key: params.img[0].img_key,
        };
        let module = [];
        params.module.PIC.forEach((item) => {
          module.push({
            type: 'PIC',
            pic: {
              upload_channel: item.upload_channel,
              bucket: item.bucket,
              img_key: item.img_key,
            },
          });
        });
        params.module.VIDEO.forEach((item) => {
          module.push({
            type: 'VIDEO',
            video_id: item.video_id,
          });
        });
        params.module = module;
        params.company_id = parseInt(params.company_id);
        params.category_id = parseInt(params.category_id);

        return params;
      };

      const ok = (val) => {
        actForm.value.setFormState('tasks', val);
      };

      const showTaskModal = (record) => {
        taskmodal.value.visible = true;
        state.modalTask = record || null;
      };

      const changeStatus = (status, record) => {
        record.status = status;
      };

      const getFormState = (val) => {
        state.modalTasks = val.tasks;
      };

      return {
        beforeSubmit,
        afterSubmit,
        taskmodal,
        actForm,
        ok,
        showTaskModal,
        ...toRefs(state),
        changeStatus,
        getFormState,
      };
    },
  };
</script>
